const express = require('express')
const router = express.Router()
const UserModel = require('../models/UserModel')
const db = require('../db/db')

db(() => {
  router.get('/select', (req, res) => {
    const {pageNum, pageSize, name} = req.query
    const regex = new RegExp(name, 'i')
    UserModel.find({
      $or: [{name: regex}], $and: [{is_show: 1}]
    }).select({
      __v: 0,
    }).sort({date: -1}).skip((pageNum - 1) * pageSize).limit(pageSize).then(data => {
      UserModel.find({
        $or: [{name: regex}], $and: [{is_show: 1}]
      }).select({
        __v: 0,
      }).sort({date: -1}).then(data2 => {
        res.send({
          code: 200, data, total: data2.length, message: 'Success'
        })
      })
    })
  })
  router.get('/selectDetail', (req, res) => {
    const {id} = req.query
    UserModel.findById(id).select({
      __v: 0,
    }).then(data => {
      res.send({
        code: 200, data, total: 1, message: 'Success'
      })
    })
  })
  router.post('/add', (req, res) => {
    const {name, age, gender} = req.body
    UserModel.create({
      name, age, gender, is_show: 1, date: new Date()
    }).then(() => {
      res.send({
        code: 200, data: true, message: 'Success'
      })
    })
  })
  router.post('/update', (req, res) => {
    const {name, age, gender, id} = req.body
    UserModel.updateOne({id}, {
      name, age, gender
    }).then(() => {
      res.send({
        code: 200, data: true, message: 'Success'
      })
    })
  })
  router.post('/delete', (req, res) => {
    const {id} = req.body
    UserModel.updateOne({_id: id}, {
      is_show: 0
    }).then((data) => {
      res.send({
        code: 200, data: true, message: 'Success'
      })
    })
  })
})

module.exports = router
